package cn.com.headfree.util;

import java.util.Date;
import java.util.UUID;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.gta.edu.sdk.config.DateJsonValueProcessor;
import com.sgcc.isc.ualogin.client.IscServiceTicketValidator;
import com.sgcc.isc.ualogin.client.util.IscSSOResourceUtil;
import com.sgcc.isc.ualogin.client.vo.IscSSOUserBean;

import cn.com.headfree.base.config.LogLevel;
import cn.com.headfree.base.config.LogType;
import cn.com.headfree.base.entity.LogInfo;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
@Component
public class RestCall {
	private static final Logger LOG = LogManager.getLogger(RestCall.class);
	private static String serviceValidate;
	
	@Value("${isc.sso.serviceValidate}")
	public void setServiceValidate(String serviceValidate) {
		RestCall.serviceValidate = serviceValidate;
	}


	public static IscSSOUserBean getIscSSOUserBean(String ticket,String url) {
		/* ticket校验器 */
		IscServiceTicketValidator sv = new IscServiceTicketValidator();
		/* 统一认证服务端校验器地址 */
		sv.setCasValidateUrl(RestCall.serviceValidate);
		/* 业务系统LoginModule访问地址 */
		sv.setService(url);
		/* 设置Ticket */
		sv.setServiceTicket(ticket);
		LogInfo logInfo = new LogInfo();
		String logId = UUID.randomUUID().toString();
		logInfo.setId(logId);
		logInfo.setDip("user-auth-server");
		logInfo.setDip_service("/user-auth-server/user/getLoginUser");
		logInfo.setLogType(LogType.receive.toString());
		logInfo.setTime(new Date());
		JsonConfig cfg = new JsonConfig();
		cfg.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor());
		try {
			sv.validate();
			sv.getResponse();
			if (sv.isAuthenticationSuccesful()) {
				IscSSOUserBean user = IscSSOResourceUtil.transferIscUserBean(sv.getUser());
				String loginUserAuthStr = null;
				if (user != null) {
					loginUserAuthStr = JSONObject.fromObject(user).toString();
				}
				logInfo.setLevel(LogLevel.INFO.toString());
				logInfo.setLogMessage(loginUserAuthStr);
				LOG.info(JSONObject.fromObject(logInfo, cfg).toString());
				return user;
			}
		} catch (Exception e) {
			logInfo.setLevel(LogLevel.ERROR.toString());
			logInfo.setLogMessage(e.getMessage());
			LOG.error(JSONObject.fromObject(logInfo, cfg).toString(),e);
		} 
		return null;
	}
}
